package com.cz.modules.rll.service.impl;

import cn.hutool.core.date.DateUtil;
import com.cz.common.utils.HCKNetSDKUtil;
import com.cz.modules.cll.entity.CllVehicleRecordEntity;
import com.cz.modules.rll.entity.RllDayInfoEntity;
import com.cz.modules.rll.entity.RllPlaceEntity;
import com.cz.modules.rll.service.RllDayInfoService;
import com.cz.modules.rll.service.RllPlaceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cz.common.utils.PageUtils;
import com.cz.common.utils.Query;

import com.cz.modules.rll.dao.RllHourCountDao;
import com.cz.modules.rll.entity.RllHourCountEntity;
import com.cz.modules.rll.service.RllHourCountService;


@Service("rllHourCountService")
public class RllHourCountServiceImpl extends ServiceImpl<RllHourCountDao, RllHourCountEntity> implements RllHourCountService {
    @Autowired
    private RllPlaceService rllPlaceService;
    @Autowired
    private RllDayInfoService rllDayInfoService;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<RllHourCountEntity> page = this.page(
                new Query<RllHourCountEntity>().getPage(params),
                new QueryWrapper<RllHourCountEntity>()
        );
        return new PageUtils(page);
    }

    @Override
    public List<RllHourCountEntity> peoplecount(String startTime,String endTime) {
        List<RllHourCountEntity> list=new ArrayList<>();
        //String type= (String) params.get("type");
        //所有卡口 去除厕所
        List<RllPlaceEntity> placelist=rllPlaceService.list(
                new QueryWrapper<RllPlaceEntity>()
                .eq("type","0")
        );
        List<String> placeid=new ArrayList<>();
        for (RllPlaceEntity place:placelist) {
            placeid.add(place.getId());
        }
        //该卡口所有数据
        List<RllHourCountEntity> rllcountlist=this.list(
                new QueryWrapper<RllHourCountEntity>()
                        .ge("start_time",startTime)
                        .le("end_time",endTime)
                        .in("place_id",placeid)
        );
        int scount=0;
        int ncount=0;
        for (RllHourCountEntity rll:rllcountlist) {
            if("南区".equals(rll.getArea())){
                scount +=rll.getEnterNum();
            }else if("北区".equals(rll.getArea())){
                ncount +=rll.getEnterNum();
            }
        }
        RllHourCountEntity en=new RllHourCountEntity();
        en.setArea("南区");
        en.setCount(scount);
        RllHourCountEntity en1=new RllHourCountEntity();
        en1.setArea("北区");
        en1.setCount(ncount);
        list.add(en);
        list.add(en1);
        return list;
    }

   /* @Override
    public void getHourCountKLBySDK() {
        //获取客流卡口列表
        List<RllPlaceEntity> placeList=rllPlaceService.list();
        for (RllPlaceEntity place:placeList) {
            Integer iUserId=-1;
            if (HCKNetSDKUtil.lUserIDMap.containsKey(place.getCameraIp())){
                iUserId=HCKNetSDKUtil.lUserIDMap.get(place.getCameraIp());
            }
            if(iUserId==-1){
                iUserId=HCKNetSDKUtil.login(place.getCameraIp());
                HCKNetSDKUtil.lUserIDMap.put(place.getCameraIp(),iUserId);
            }
            if(iUserId!=-1){
                Calendar c=Calendar.getInstance();
                c.add(Calendar.HOUR,-1);
                String date= DateUtil.format(c.getTime(),"yyyy-MM-dd");
                String startTime=date+ " 00:00:00";
                String endTime=DateUtil.format(c.getTime(),"yyyy-MM-dd HH");
                endTime+= ":00:00";
                c.setTime(DateUtil.parse(startTime));
                List<String> timeStr=new ArrayList<>();
                for (Long i = c.getTimeInMillis(); i <=DateUtil.parse(endTime).getTime() ; i=c.getTimeInMillis()) {
                    timeStr.add(DateUtil.format(c.getTime(),"yyyy-MM-dd HH:mm:ss"));
                    c.add(Calendar.HOUR,1);
                }
                List<RllHourCountEntity> cList=this.list(new QueryWrapper<RllHourCountEntity>().ge("start_time",date+" 00:00:00").eq("place_id",place.getId()));

                List<RllHourCountEntity> hourCountList=new ArrayList<>();
                try{
                    hourCountList= HCKNetSDKUtil.getPDCResult(place.getCameraIp(),iUserId,date+" 0:0:0",date+ " 23:59:59");
                }catch (Exception e){
                    e.printStackTrace();
                };
                for (String time:timeStr) {
                    boolean bl= true;
                    //判断是否存储过
                    for (RllHourCountEntity cl:cList) {
                        if(DateUtil.format(cl.getStartTime(),"yyyy-MM-dd HH:mm:ss").equals(time)){
                            bl=false;
                        }
                    }
                    //如果没存储
                    if(bl){
                        for (RllHourCountEntity hourCount:hourCountList) {
                            if (DateUtil.format(hourCount.getStartTime(),"yyyy-MM-dd HH:mm:ss").equals(time)){
                                RllHourCountEntity hc=new RllHourCountEntity();
                                hc.setArea(place.getArea());
                                hc.setPlaceId(place.getId());
                                hc.setStartTime(hourCount.getStartTime());
                                hc.setEndTime(hourCount.getEndTime());
                                hc.setEnterNum(hourCount.getEnterNum());
                                hc.setLeaveNum(hourCount.getLeaveNum());
                                this.save(hc);
                            }
                        }
                    }

                }
            }
        }
    }*/
   @Override
   public void getHourCountKLBySDK() {
       //获取客流卡口列表
       List<RllPlaceEntity> placeList=rllPlaceService.list();
       for (RllPlaceEntity place:placeList) {
           Integer iUserId=-1;
           if (HCKNetSDKUtil.lUserIDMap.containsKey(place.getCameraIp())){
               iUserId=HCKNetSDKUtil.lUserIDMap.get(place.getCameraIp());
           }
           if(iUserId==-1){
               iUserId=HCKNetSDKUtil.login(place.getCameraIp());
               HCKNetSDKUtil.lUserIDMap.put(place.getCameraIp(),iUserId);
           }
           if(iUserId!=-1){
               Calendar c=Calendar.getInstance();
               c.add(Calendar.HOUR,-1);
               String date= DateUtil.format(c.getTime(),"yyyy-MM-dd");
               String startTime=date+ " 00:00:00";
               String endTime=DateUtil.format(c.getTime(),"yyyy-MM-dd HH");
               endTime+= ":00:00";
               c.setTime(DateUtil.parse(startTime));
               List<String> timeStr=new ArrayList<>();
               for (Long i = c.getTimeInMillis(); i <=DateUtil.parse(endTime).getTime() ; i=c.getTimeInMillis()) {
                   timeStr.add(DateUtil.format(c.getTime(),"yyyy-MM-dd HH:mm:ss"));
                   c.add(Calendar.HOUR,1);
               }
               //List<RllHourCountEntity> cList=this.list(new QueryWrapper<RllHourCountEntity>().ge("start_time",date+" 00:00:00").eq("place_id",place.getId()));
               this.remove(new QueryWrapper<RllHourCountEntity>().ge("start_time",date+" 00:00:00").eq("place_id",place.getId()));

               List<RllHourCountEntity> hourCountList=new ArrayList<>();
               try{
                   hourCountList= HCKNetSDKUtil.getPDCResult(place.getCameraIp(),iUserId,date+" 0:0:0",date+ " 23:59:59");
               }catch (Exception e){
                   e.printStackTrace();
               };
               for (String time:timeStr) {
                   boolean bl= true;
                   //判断是否存储过
                    /*for (RllHourCountEntity cl:cList) {
                        if(DateUtil.format(cl.getStartTime(),"yyyy-MM-dd HH:mm:ss").equals(time)){
                            bl=false;
                        }
                    }*/
                   //如果没存储
                   if(bl){
                       for (RllHourCountEntity hourCount:hourCountList) {
                           if (DateUtil.format(hourCount.getStartTime(),"yyyy-MM-dd HH:mm:ss").equals(time)){
                               RllHourCountEntity hc=new RllHourCountEntity();
                               hc.setArea(place.getArea());
                               hc.setPlaceId(place.getId());
                               hc.setStartTime(hourCount.getStartTime());
                               hc.setEndTime(hourCount.getEndTime());
                               hc.setEnterNum(hourCount.getEnterNum());
                               hc.setLeaveNum(hourCount.getLeaveNum());
                               this.save(hc);
                           }
                       }
                   }

               }
           }
       }
   }

    @Override
    public  List  kllChart(String area,String type) {
        Calendar calendar=Calendar.getInstance();
        Map<String,Integer> map=new HashMap<String,Integer>();
        List list=new ArrayList();
        //if("0".equals(type)){
            calendar.add(Calendar.HOUR,-24);
            String startTime=DateUtil.format(calendar.getTime(),"yyyy-MM-dd HH");
            List<RllHourCountEntity> hourCountList=this.list(new QueryWrapper<RllHourCountEntity>().eq("area",area).ge("start_time",startTime+":00:00"));
            List<String> timeList=new ArrayList<>();
            for (int i = 0; i <24 ; i++) {
                timeList.add(DateUtil.format(calendar.getTime(),"yyyy-MM-dd HH")+":00");
                calendar.add(Calendar.HOUR,1);
            }
            for (RllHourCountEntity hourCount:hourCountList) {
                if(map.containsKey(DateUtil.format(hourCount.getStartTime(),"yyyy-MM-dd HH:mm"))){
                    String key=DateUtil.format(hourCount.getStartTime(),"yyyy-MM-dd HH:mm");
                    Integer count=map.get(key);
                    count+=hourCount.getEnterNum();
                }else {
                    map.put(DateUtil.format(hourCount.getStartTime(),"yyyy-MM-dd HH:mm"),hourCount.getEnterNum());
                }
            }
            List<Integer> valueList=new ArrayList<>();
            for (String time:timeList) {
                if(!map.containsKey(time)){
                    valueList.add(0);
                }else {
                    valueList.add(map.get(time));
                }
            }

            list.add(timeList);
            list.add(valueList);
       // }
        return list;
    }

    @Override
    public List kllCharthour(String area, String startTime, String endTime) {
        Long start= DateUtil.parse(startTime).getTime();
        Long end=DateUtil.parse(endTime).getTime();
        Calendar calendar=Calendar.getInstance();
        calendar.setTime(new Date(start));
        List<Long> timeList=new ArrayList<>();
        for (Long i = start; i <end ; i=calendar.getTimeInMillis()) {
            calendar.add(Calendar.HOUR,1);
            timeList.add(calendar.getTimeInMillis());
        }
        //查询非厕所客流相机
        List<RllPlaceEntity> placeList=rllPlaceService.list(
                new QueryWrapper<RllPlaceEntity>().eq("area",area).eq("type","0")
        );
        List<String> placeIds=new ArrayList<>();
        for (RllPlaceEntity palce:placeList) {
            placeIds.add(palce.getId());
        }
        List<RllHourCountEntity> RecordList=this.list(
                new QueryWrapper<RllHourCountEntity>()
                        .in("place_id",placeIds)
                        .ge("start_time",startTime)
                        .lt("end_time",endTime)
                .orderByAsc("start_time")
        );
        List<Integer> valueList=new ArrayList<>();
        Long s=start;
        List<String> timeStrList=new ArrayList<>();
        for (int i = 0; i <timeList.size() ; i++) {
            timeStrList.add(DateUtil.format(new Date(timeList.get(i)),"HH:mm"));
            Integer count=0;
            for (RllHourCountEntity record:RecordList) {
                Long crossTime=record.getStartTime().getTime();
                if(crossTime>=s && crossTime<timeList.get(i)){
                    count +=record.getEnterNum();
                }
            }
            s=timeList.get(i);
            valueList.add(count);
        }
        List list=new ArrayList();
        list.add(timeStrList);
        list.add(valueList);
        return list;
    }

    @Override
    public List kllChartday(String area, String startTime, String endTime) {
        Long start= DateUtil.parse(startTime).getTime();
        Long end=DateUtil.parse(endTime).getTime();
        Calendar calendar=Calendar.getInstance();
        calendar.setTime(new Date(start));
        List<Long> timeList=new ArrayList<>();
        for (Long i = start; i <=end ; i=calendar.getTimeInMillis()) {
            timeList.add(calendar.getTimeInMillis());
            calendar.add(Calendar.DAY_OF_MONTH,1);
        }
        //查询非厕所客流相机
        List<RllPlaceEntity> placeList=rllPlaceService.list(
                new QueryWrapper<RllPlaceEntity>().eq("area",area).eq("type","0")
        );
        List<String> placeIds=new ArrayList<>();
        for (RllPlaceEntity palce:placeList) {
            placeIds.add(palce.getId());
        }

        List<RllHourCountEntity> RecordList=this.list(
                new QueryWrapper<RllHourCountEntity>()
                        .in("place_id",placeIds)
                        .ge("start_time",startTime)
                        .lt("end_time",endTime)
        );
        List<Integer> valueList=new ArrayList<>();
        Long s=start;
        List<String> timeStrList=new ArrayList<>();
        for (Long ltime:timeList) {
            timeStrList.add(DateUtil.format(new Date(ltime),"MM-dd"));
        }
        for (String time:timeStrList) {
            int count=0;
            for (RllHourCountEntity record:RecordList) {
                String tt=DateUtil.format(record.getStartTime(),"MM-dd");
                if(tt.equals(time)){
                    count +=record.getEnterNum();
                }
            }
            valueList.add(count);
        }
        List list=new ArrayList();
        list.add(timeStrList); list.add(valueList);


        return list;
    }

    @Override
    public List kllChart1(String area, String startTime,String endTime) {
        //查询非厕所客流相机
        List<RllPlaceEntity> placeList=rllPlaceService.list(
                new QueryWrapper<RllPlaceEntity>().eq("area",area).eq("type","0")
        );
        List<String> placeIds=new ArrayList<>();
        for (RllPlaceEntity palce:placeList) {
            placeIds.add(palce.getId());
        }
        List<RllHourCountEntity> RecordList=this.list(
                new QueryWrapper<RllHourCountEntity>()
                        .in("place_id",placeIds)
                        .ge("start_time",startTime)
                        .lt("end_time",endTime)
        );

        Long start= DateUtil.parse(startTime).getTime();
        Long end=DateUtil.parse(endTime).getTime();
        Calendar calendar=Calendar.getInstance();
        calendar.setTime(new Date(start));
        List<Long> timeList=new ArrayList<>();
        for (Long i = start; i <=end ; i=calendar.getTimeInMillis()) {
            calendar.add(Calendar.HOUR,1);
            timeList.add(calendar.getTimeInMillis());

        }
        List<Integer> valueList=new ArrayList<>();
        Long s=start;
        List<String> timeStrList=new ArrayList<>();
        for (Long ti:timeList){
            timeStrList.add(DateUtil.format(new Date(ti),"HH:mm"));
        }
        for (int i = 0; i <timeList.size()-1 ; i++) {//最后一小时没数据另外处理
            Integer count=0;
            for (RllHourCountEntity record:RecordList){
                Long sTime=record.getStartTime().getTime();
                Long eTime=record.getEndTime().getTime();
               if(sTime>=s && eTime< timeList.get(i)){
                   count+=record.getEnterNum();
               }
            }
            s=timeList.get(i);
            valueList.add(count);
        }
        //最后一小时数据
        Date date= new Date(end);
        String queryTime=DateUtil.format(date,"yyyy-MM-dd HH")+":00:00";
        List<RllDayInfoEntity> infoList=rllDayInfoService.list(
                new QueryWrapper<RllDayInfoEntity>().in("place_id",placeIds).ge("data_time",queryTime)
        );
        Integer lastCount=0;
        for (RllDayInfoEntity info:infoList) {
            lastCount+=info.getEnterNum();
        }
        Integer midCount=0;
        for (Integer val:valueList) {
            midCount+=val;
        }
        if(lastCount-midCount>=0){
            valueList.add(lastCount-midCount);
        }else {
            valueList.add(0);
        }
        Integer totalCount=0;
        for (Integer t:valueList) {
            totalCount+=t;
        }
        List list=new ArrayList();
        list.add(timeStrList);
        list.add(valueList);
        list.add(totalCount);
        return list;
    }

    @Override
    public Integer kllCount(String startTime, String endTime, List<RllPlaceEntity> list) {
        List<String> palceIdList=new ArrayList<>();
        for (RllPlaceEntity place:list) {
            palceIdList.add(place.getId());
        }
        Integer count=0;
        List<RllHourCountEntity> hourCountList=this.list(new QueryWrapper<RllHourCountEntity>().ge("start_time",startTime).le("end_time",endTime).in("place_id",palceIdList));
        for (RllHourCountEntity rllHourCount:hourCountList) {
            count+=rllHourCount.getEnterNum();
        }
        return count;
    }
}
